﻿using System;
using Castle.DynamicProxy;

namespace AspectMap.StandardAspects
{
    public class ExceptionAttributeHandler : AttributeHandler
    {
        public ExceptionAttributeHandler(IExceptionHandler exceptionHandler)
        {
            ExceptionHandler = exceptionHandler;
        }

        public IExceptionHandler ExceptionHandler { get; set; }

        public override Action<IInvocation> Surround(Action<IInvocation> invocation, Attribute sourceAttribute)
        {
            return i =>
            {
                try
                {
                    invocation(i);
                }
                catch (Exception ex)
                {
                    if (!(ex is HandledException))
                    {
                        ExceptionHandler.HandleException(ex);
                        throw new HandledException(ex);
                    }
                    throw;
                }
            };
        }
    }
}
